package org.aurora.remote.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import org.aurora.remote.protocol.RemoteSerializableUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 解码器
 * maxFrameLength – 帧的最大长度。 如果帧的长度大于该值，将抛出 TooLongFrameException。
 * lengthFieldOffset – 帧长度的起始位置
 * lengthFieldLength – 帧的长度所占的字节数
 * lengthAdjustment – 添加到长度字段值的补偿值 todo 该字段含义
 * initialBytesToStrip – 丢弃的起始字节数
 **/

public class NettyDecoder extends LengthFieldBasedFrameDecoder {
    private static final Logger log = LoggerFactory.getLogger(NettyDecoder.class);

    public NettyDecoder() {
        super(8388608, 0, 4, 0, 4);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) {
        ByteBuf frame = null;

        try {
            frame = (ByteBuf) super.decode(ctx, in);

            if (frame == null) {
                return null;
            }

            return RemoteSerializableUtil.deSerialize(frame.nioBuffer());
        } catch (Exception e) {
            log.error("NettyDecoder byteBuf decode error ", e);
        } finally {
            if (frame != null) {
                frame.release();
            }
        }
        return null;
    }
}
